package org.garbagecan.xstreamstudy.json;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.garbagecan.xstreamstudy.alias.Blog;
import org.garbagecan.xstreamstudy.sample1.Application;
import org.garbagecan.xstreamstudy.sample1.FavoriteApplications;
import org.garbagecan.xstreamstudy.sample1.StartCenter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;

public class Test {
	public static void main(String[] args) throws Exception {
		test();
	}
	
	public static void test() {
		XStream xstream = null;
		
		A a = getA();
		xstream = new XStream(new JsonHierarchicalStreamDriver() {
			public HierarchicalStreamWriter createWriter(Writer writer) {
				return new JsonWriter(writer);
			}
		});
		xstream.setMode(XStream.NO_REFERENCES);
		xstream.alias("a", A.class);
		xstream.alias("b", B.class);
		xstream.alias("c", C.class);
		String json = xstream.toXML(a);
		System.out.println(json);
		
		xstream = new XStream(new JettisonMappedXmlDriver());
		xstream.setMode(XStream.NO_REFERENCES);
		xstream.alias("a", A.class);
		xstream.alias("b", B.class);
		xstream.alias("c", C.class);
		xstream.addImplicitCollection(B.class, "cs", C.class);
		A anotherA = (A)xstream.fromXML(json);
		System.out.println(anotherA);
		System.out.println(anotherA.getB().getDate());
	}
	
	private static A getA() {
		B b = new B();
		b.setId("b_id");
		b.setName("b_name");
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, 2000);
		cal.set(Calendar.MONDAY, 0);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		b.setDate(cal.getTime());
		List<C> cs = new ArrayList<C>();
		for (int i = 0; i < 3; i++) {
			C c = new C();
			c.setId("c_id");
			c.setName("c_name");
			cs.add(c);
		}
		b.setCs(cs);

		A a = new A();
		a.setId("a_id");
		a.setName("a_name");
		a.setB(b);
		
		return a;
	}
}
